package com.cn.qtms.controller;

import com.cn.qtms.base.controller.BaseJpaController;
import com.cn.qtms.common.result.Result;
import com.cn.qtms.common.result.ResultUtil;
import com.cn.qtms.common.tree.Tree;
import com.cn.qtms.exception.AppException;
import com.cn.qtms.feign.SysService;
import com.cn.qtms.model.JwtUser;
import com.cn.qtms.util.ConvertUtils;
import com.cn.qtms.util.OpenHelper;
import com.cn.qtms.entity.vo.sys.Resource;
import com.cn.qtms.entity.vo.sys.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

;

/**
 * Created by SuperS on 2017/9/25.
 *
 * @author SuperS
 */
@RestController
public class UserController extends BaseJpaController {

    @Autowired
    HttpServletRequest request;
    @Autowired
    SysService sysService;
    @Autowired
    private RedisTemplate redisTemplate;
    //加密解密
    /**
     *
     */
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @GetMapping("/user")
    public Result<User> user(Principal user) {
        User result = new User();
        JwtUser jwtUser = OpenHelper.getUser();
        BeanUtils.copyProperties(jwtUser, result);
        //说明是商户 需要更新商户id
        if ("2".equals(result.getUserType())) {
            User tsUser = sysService.findByUserName(result.getUsername());
            if (tsUser.getClientId() == null) {
                throw new AppException("当前商户没有商户名称");
            }
            result.setClientId(tsUser.getClientId().toString());
        }
        List<String> collect = jwtUser.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        result.setRoles(collect);
        //获取角色对应的权限
        List<Tree<Resource>> trees = sysService.findRoleResource(new HashSet<>(collect));
        result.setResources(trees);
        List<String> permissionList = sysService.findRolePermission(new HashSet<>(collect));
        result.setPermissionList(permissionList);
        return ResultUtil.success(result);
    }

    @GetMapping("/info")
    public Map<String, Object> info(Authentication authentication) {
        JwtUser user = OpenHelper.getUser();
        return ConvertUtils.objectToMap(user);
    }


    @GetMapping("remove_token")
    public Result<Boolean> removeToken(@RequestParam("access_token") String accessToken) {
        consumerTokenServices.revokeToken(accessToken);
        return ResultUtil.success(true);
    }

    @GetMapping("limitedToken")
    public String limitedToken(@RequestParam("token") String token) {
        redisTemplate.opsForValue().set("limitToken_" + token, token);
        //设置10s只能访问1次
        redisTemplate.expire("limitToken_" + token, 10, TimeUnit.SECONDS);
        return "success";
    }

    @GetMapping("checkLimited")
    public Boolean checkLimited(@RequestParam("token") String token) {
        if (redisTemplate.hasKey("limitToken_" + token)) {
            return true;
        }
        return false;
    }
}

